#include <common.h>
#include <multiboot.h>

extern unsigned int endkernel;

void map_memory(memory_map_t *ptr, int length)
{
	ptr += 5;
	length += 5;
}

void init_mman()
{
	print("\nNo triple fault yet!\n");
	unsigned int end = (unsigned int)&endkernel;
	//Get the page-aligned beginning for the page table, right after the kernel space ends
	unsigned int page_aligned_end = (end & 0xFFFFF000) + 0x1000;
	unsigned int *page_directory = (unsigned int*)page_aligned_end;
	// Set up the page directory
	int i;
	for (i = 0; i < 1024; i++)
	{
		//Supervisor level, read/write not present
		page_directory[i] = 0 | 2;
	}
	
	//Set up the first page table
	unsigned int *first_page_table = page_directory + 0x1000;
	unsigned int address = 0;
	for (i = 0; i < 1024; i++)
	{
		first_page_table[i] = address | 3;
		address += 4096;
	}
	page_directory[0] = *first_page_table;
	page_directory[0] |= 3;
	
	print("\nPage dir start: 0x");
	print(itoa((unsigned int)page_directory, 16));
	print("\nPage table end: 0x");
	print(itoa((unsigned int) first_page_table, 16));
	print("\n");
	
	asm volatile("mov %0, %%cr3":: "b"(page_directory));
	unsigned int cr0;
	asm volatile("mov %%cr0, %0": "=b"(cr0));
	cr0 |= 0x80000000;
	//Error flipping
	/*asm volatile("mov %0, %%cr0":: "b"(cr0));*/
}